package com.dmx.cep.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 字幕文件解析工具类
 * @author magicyang
 *
 */
public class CaptionTextParse {
	private Log log=LogFactory.getLog(this.getClass());
	
	private String encoding;
	
	private List<String> lines;
	
	private boolean errorFlag = false;
	
	private String errorCode;
	
	private int errorLine=0;
	
	private final String CAPTION_TIME_BREAKE_FLAG = " --> ";
	
	private static final  String timePattern="^(0([0-9])|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]),([0-9][0-9][0-9]) --> (0([0-9])|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]),([0-9][0-9][0-9])$";
	
	public CaptionTextParse(){}
	
	public CaptionTextParse(InputStream is,String encoding) throws IOException{
		this.encoding=encoding;
		lines=IOUtils.readLines(is,encoding);
	}

	public CaptionTextParse(Reader re) throws IOException{
		lines=IOUtils.readLines(re);
	}	
	
	public String parse(){
		//lines=removeLastEmptyLines(lines);   //去掉文件末尾空行
		StringBuffer sb=new StringBuffer();
		
		if(lines==null||lines.size()==0){
			errorCode="no.caption.to.import";
			errorFlag=true;
			return null;
		}
		
		
		String firstLine=lines.get(0);
		try {
			byte[] bytes=firstLine.getBytes(encoding);
			
			for(int i=0;i<bytes.length;i++){
				if(i>0) break;
				int temp=bytes[i];
				String hexString=Integer.toHexString(temp);
				if(hexString.length()<2) break;
				// 1个byte变成16进制的，只需要2位就可以表示了，取后面两位，去掉前面的符号填充
				hexString=hexString.substring(hexString.length()-2);
				log.info(hexString.toUpperCase());
				if(hexString.toUpperCase().equals("EF")){
					firstLine=new String(bytes,3,bytes.length-3,"UTF-8");  //去掉BOM字符
					break;
				}
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error(e);
		}
		
		//log.info("firstLine="+firstLine+",length="+firstLine.length());
		
		lines.set(0, firstLine);
		
		int dataLength=lines.size();
		
		for(int i=0;i<dataLength;i++){
			String line=lines.get(i).trim();
			
			if(!"".equals(line)){
				
				try{
					Integer.parseInt(line);
				}catch(Exception e){
					errorFlag=true;
					errorCode="caption.parse.error";
					errorLine=i+1;
					return null;
				}
				
				if(i<dataLength-1){
					i++;
					String nextLine=lines.get(i).trim();
					if(isWrongPattern(timePattern, nextLine)){
						errorFlag=true;
						errorCode="caption.parse.error";
						errorLine=i+1;
						return null;
					}else{
						while(true){
							i++;
							if(i>=dataLength) break;
							nextLine=lines.get(i).trim();
							if("".equals(nextLine)) break;
						}
					}
				}
			}
		}
		
		/**
		 * 1.检查字幕时间的上一行必须是Index(数字)
		 */
		for(int i=0;i<dataLength;i++){
			String line=lines.get(i).trim();
			/*line=TextFilter.filter(line);
			sb.append(line+"\r\n");*/
			
			if(!isWrongPattern(timePattern, line)&&i>0){
				String previousLine=lines.get(i-1).trim();
				try{
					Integer.parseInt(previousLine);
				}catch(Exception e){
					errorFlag=true;
					errorCode="caption.parse.error";
					errorLine=i;
					return null;
				}
			}
		}
		
		return sb.toString();
	}
	
	private List<String> removeLastEmptyLines(List<String> lines){
		if(lines==null||lines.size()==0){
			return lines;
		}else if("".equals(lines.get(lines.size()-1).trim())){
			lines=lines.subList(0, lines.size()-1);
			
			return removeLastEmptyLines(lines);
		}else{
			return lines;
		}
	}
	
	private List<String> removeFirstEmptyLines(List<String> lines){
		if(lines==null||lines.size()==0){
			return lines;
		}else if("".equals(lines.get(0).trim())){
			lines=lines.subList(1, lines.size());
			
			return removeFirstEmptyLines(lines);
		}else{
			return lines;
		}
	}
	
	private boolean isWrongPattern(String pattern,String context){
		Pattern p=Pattern.compile(pattern);
		Matcher m=p.matcher(context);
		if(m.matches()){
			return false;
		}
		return true;
	}

	public List<String> getLines() {
		return lines;
	}

	public void setLines(List<String> lines) {
		this.lines = lines;
	}

	public boolean isErrorFlag() {
		return errorFlag;
	}

	public void setErrorFlag(boolean errorFlag) {
		this.errorFlag = errorFlag;
	}

	public String getErrorCode() {
		return errorCode;
	}

	public void setErrorCode(String errorCode) {
		this.errorCode = errorCode;
	}
	
	public static void main(String[] args){
		CaptionTextParse parse=new CaptionTextParse();
		
		System.out.println(parse.isWrongPattern(timePattern, "00:00:01,799 --> 00:00:02,900"));
	}

	public int getErrorLine() {
		return errorLine;
	}

	public void setErrorLine(int errorLine) {
		this.errorLine = errorLine;
	}
	
}
